package com.study.sbsummary.config.database.shadow;

import com.study.sbsummary.context.RequestContext;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class TruelyRoutingDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        if (RequestContext.isOnlineTest()) {
            return DbTypeHolder.DbType.SHADOW;
        }
        return DbTypeHolder.DbType.MAIN;
    }

    public static AbstractRoutingDataSource proxyDataSource(DataSource mainDataSource,
                                                            DataSource shadowDataSource) {
        TruelyRoutingDataSource dbSourceSplit = new TruelyRoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DbTypeHolder.DbType.MAIN, mainDataSource);
        targetDataSources.put(DbTypeHolder.DbType.SHADOW, shadowDataSource);
        dbSourceSplit.setDefaultTargetDataSource(mainDataSource);
        dbSourceSplit.setTargetDataSources(targetDataSources);
        dbSourceSplit.afterPropertiesSet();
        return dbSourceSplit;
    }
}
